<?php

class Crud_Form_Element_Many2many extends Crud_Form_Element
{
	/**
	 * Primary table for creating element.
	 * 
	 * @var Crud_Db_Table_Abstract
	 */
	protected $_table;
	
	/**
	 * Dependent many2many table.
	 * 
	 * @var Crud_Db_Table_Abstract 
	 */
	protected $_m2mTable;
	
	public function __construct($table, $m2mTable)
	{
		if (!$table instanceof Crud_Db_Table_Abstract) {
			$message = 'Cant create many2many element. Primary table is invalid Crud_Db_Table';
			throw new Crud_Exception($message);
		}
		
		if (!$m2mTable) {
			$message = 'Cant create many2many element. Dependent table is invalid Crud_Db_Table';
			throw new Crud_Exception($message);
		}

		$this->_table = $table;
		$this->_m2mTable = $m2mTable;
		
		$this->init();
	}
	
	/**
	 * Return primary table for creating element.
	 * 
	 * @return Crud_Db_Table_Abstract
	 */
	public function getTable()
	{
		return $this->_table;
	}
	
	/**
	 * Dependent many2many table.
	 * 
	 * @return Crud_Db_Table_Abstract 
	 */
	public function getM2mTable()
	{
		return $this->_m2mTable;
	}
	
	/**
	 * Create form element.
	 * 
	 * @return void
	 */
	public function init()
	{
		$table = $this->getTable();
		$m2mTable = $this->getM2mTable();
		
		// Setup columns in many2many table.
		$column = $m2mTable->getFKColumnFor($table);
		$column3rd = $m2mTable->getFKColumnNotFor($table);
		
		// Create Zend_Form_Element
		$name = $m2mTable->info(Zend_Db_Table_Abstract::NAME);
		$element = new Zend_Form_Element_MultiCheckbox($name);
		
		// Set options
		$values = $column3rd->getFKValues();
		$element->setMultiOptions($values);
		$this->setElement($element);
	}
}